package filters

import (
	"UpdateManagerServer/dbmgr"
	"encoding/json"
	"strings"
	"time"

	"github.com/beego/beego/v2/core/logs"
	"github.com/beego/beego/v2/server/web/context"
)

var CheckToken = func(ctx *context.Context) {
	// 白名单路径配置
	allowPaths := []string{
		"/api/other",
		"/api/register",
		"/api/login",
	}

	currentPath := ctx.Request.RequestURI

	notAllowPaths := []string{
		//"/api/file/list",
	}

	for _, path := range notAllowPaths {
		if strings.HasPrefix(currentPath, path) {
			ctx.Output.SetStatus(401)
			ctx.Output.JSON(map[string]string{
				"error": "Invalid token",
			}, false, false)
			return
		}
	}

	// 检查当前路径是否需要跳过验证
	for _, path := range allowPaths {
		if strings.HasPrefix(currentPath, path) {
			return // 直接放行白名单路径
		}
	}

	tokenStr := ctx.Input.Header("Authorization")
	if tokenStr == "" {
		ctx.Output.SetStatus(401)
		ctx.Output.JSON(map[string]string{
			"error": "Missing token",
		}, false, false)
		return
	}

	//logs.Info("token:%s", tokenStr)

	//管理员token
	if tokenStr == "b22b5e61-be32-4b98-88cb-bb8c48df74ba" {
		return
	}

	token, err := dbmgr.GlobalBaseRepo.GetByToken(tokenStr)

	// 验证逻辑
	if err != nil || token.IsRevoked || time.Now().After(token.ExpiredAt) {
		ctx.Output.SetStatus(401)
		ctx.Output.JSON(map[string]string{
			"error": "Invalid token",
		}, false, false)
		return
	}

	permision, err := dbmgr.GlobalBaseRepo.Get_employeeByID(token.User.ID)
	if err != nil {
		logs.Error(err.Error())

		ctx.Output.SetStatus(402)
		ctx.Output.JSON(map[string]string{
			"error": "查询用户权限失败",
		}, false, false)
		return
	}

	if permision.IsAdmin == 1 {

	} else {
		var mapPerMission map[string]string

		err = json.Unmarshal([]byte(permision.Permission), &mapPerMission)
		if err != nil {
			logs.Error(err.Error())
			ctx.Output.SetStatus(402)
			ctx.Output.JSON(map[string]string{
				"error": "查询用户权限失败,权限信息不符合json格式",
			}, false, false)
			return
		}

		adminPermissionPaths := []string{
			"/api/employee/update",
			"/api/employee/list",
		}

		for _, path := range adminPermissionPaths {
			if strings.HasPrefix(currentPath, path) {
				logs.Error("需要管理员权限")
				ctx.Output.SetStatus(402)
				ctx.Output.JSON(map[string]string{
					"error": "需要管理员权限",
				}, false, false)
				return
			}
		}

		editPermissionPaths := []string{
			"/api/mashine/create",
			"/api/file/delete",
			"/api/file/rename",
			"/api/upload/chunk",
			"/api/upload/merge",
			"/api/version/create",
			"/api/version/delete",
		}

		for _, path := range editPermissionPaths {
			if strings.HasPrefix(currentPath, path) {
				value, exit := mapPerMission["machineEdit"]
				if exit && value == "1" {

				} else {
					logs.Error("需要编辑权限")
					ctx.Output.SetStatus(402)
					ctx.Output.JSON(map[string]string{
						"error": "需要编辑权限",
					}, false, false)
					return
				}
				break
			}
		}

	}

	// 更新最后活跃时间（滑动过期）
	if time.Since(token.LastActivity) > 5*time.Minute {
		token.LastActivity = time.Now()
		dbmgr.GlobalBaseRepo.UpdateToken(token)
	}

	// 将用户信息存入上下文
	ctx.Input.SetData("currentUser", token.User)
}
